/**
 * 大数相乘
 * @param num1 string
 * @param num2 string
 * @returns string
 */
export function bigMultiply(num1: string, num2: string): string {
  let len1 = num1.length,
    len2 = String(num2).length;
  let ans: number[] = [];
  for (let i = len1 - 1; i >= 0; i--) {
    for (let j = len2 - 1; j >= 0; j--) {
      let index1 = i + j;
      let index2 = i + j + 1;
      let mul = Number(num1[i]) * Number(num2[j]) + (Number(ans[index2]) || 0);
      ans[index1] = Math.floor(mul / 10) + (Number(ans[index1]) || 0);
      ans[index2] = mul % 10;
    }
  }
  let result = ans.join('');
  //这里结果有可能会是多个零的情况，需要转成数字判断
  //原来写的是return +result === 0 ? '0' : result，result字符串会出现有前置0的情况
  return +result === 0 ? '0' : result.replace(/^0+/, '');
}

/**
 * 大数相加
 * @param num1 string
 * @param num2 string
 * @returns string
 */
export function bigAdd(num1: string, num2: string): string {
  let maxLength = Math.max(num1.length, num2.length);
  //num1和num2位数对齐，位数较小的前面补0
  num1 = num1.padStart(maxLength, '0');
  num2 = num2.padStart(maxLength, '0');
  let arrA = num1.split(''),
    arrB = num2.split(''),
    carry = 0,
    sum = '';
  while (arrA.length || arrB.length || carry) {
    // @ts-ignore
    carry = carry + (~~arrA.pop() + ~~arrB.pop());
    sum = (carry % 10) + sum;
    carry = carry > 9 ? 1 : 0;
  }
  return sum.replace(/^0+/, '');
}
